<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Request;
use app\middleware\AuthAdmin;

class Exhibits
{
    protected $middleware = [AuthAdmin::class];
    // const storageStie = 'http://1.12.76.149:15002';
    const storageStie = 'https://darong.storage.1415926.com.cn';
    /**
     * 显示资源列表
     */
    public function list(){
        if(Request::isPost()){
            $zone_class=input('param.zone_class');
            $zone=input('param.zone');
            $keyword=input('param.keyword');
            $page=input('param.page',1);$page_size=input('param.page_size',25);
            $where=[];
            if($zone_class){
                $where[]=['zone_class','=',$zone_class];
            }
            if($zone){
                $where[]=['zone','=',$zone];
            }
            if($keyword){
                $where[]=['customize_code|title','like',"%$keyword%"];
            }
            $data=Db::table('exhibits')->field('id,zone_class,zone,customize_code,title,era,category,type,tex,style_mark,size,angle,check_in_at,remark,pieces,price_desc as price,is_featured')
            ->field("CONCAT('https://darong.storage.1415926.com.cn/tmp_wxacode/',customize_code,'_',title,'.png') as wxacode")
            ->where($where)
            ->paginate([
                    'list_rows' => $page_size,
                    'page'      => $page,
                ]);
    
            $total=$data->total();
            $data=$data->items();
            $result=['code'=>200,'message'=>'获取成功','success'=>true,'result'=>['list'=>$data,'total'=>$total]];
            return json($result);
        }
    }

    /**
     * 显示创建资源表
     */
    public function create(){
        //
        if(Request::isPost()){
            try{
                $cover=input('param.cover',[]);
                
                $exhibitsId=Db::table('exhibits')->insertGetId([
                    // 'zone_class'=>'',
                    // 'zone'=>'',
                    'customize_code'=>input('param.customize_code'),
                    'title'=>input('param.title'),
                    'era'=>input('param.era'),
                    'category'=>input('param.category'),
                    'type'=>input('param.type'),
                    'tex'=>input('param.tex'),
                    'style_mark'=>input('param.style_mark'),
                    'size'=>input('param.size'),
                    'angle'=>input('param.angle'),
                    'pieces'=>input('param.pieces'),
                    'remark'=>input('param.remark'),
                    'check_in_at'=>time()
                ]);
                if($exhibitsId){
                    if(count($cover)>0){
                        $cover=moveImage($cover,'exhibit',$exhibitsId);
                        Db::table('exhibits')->where(['id'=>$exhibitsId])->update(['cover'=>json_encode($cover)]);
                    }
                    $access_token=getAccessToken();
                    $scene = 'exhibitId='.$exhibitsId; // 场景值，可根据业务需要传递参数:cite[4]
                    $page = 'pages/exhibit/detail'; // 扫描小程序码后进入的页面:cite[4]
                    $savePath='/www/wwwroot/storage.darong1994.cn/tmp_wxacode/'.input('param.customize_code').'_'.input('param.title').'.png';
                    $kk=setWxacode($access_token,$scene, $page, $savePath, 430);
                }
                // $reslut=['code'=>200,'message'=>'获取成功','success'=>true];
                return json(['code'=>200,'message'=>'新增成功','success'=>true,'result'=>['id'=>$exhibitsId]]);
             }catch (Exception $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e]);
            }
        }
    }

    /**
     * 显示指定的资源
     */
    public function detail(){
        if(Request::isPost()){
            $id=input('param.id');
            $detail=Db::table('exhibits')->where(['id'=>$id])->find();
            $detail['cover']=$detail['cover']?json_decode($detail['cover'],true):[];
            $detail['tmp_cover']=[];
            foreach($detail['cover'] as $key=>$value){
                $detail['tmp_cover'][]=['name'=>time().$key,'url'=>'https://darong.storage.1415926.com.cn/'.$value];
            }
            // $detail['tmp_cover']=$detail['cover']?json_decode($detail['cover'],true):[];
            $result=['code'=>200,'message'=>'获取成功','success'=>true,'result'=>$detail];
            return json($result);
        }
    }

    /**
     * 显示编辑资源表单页.
     */
    public function edit(){
        if(Request::isPost()){
            try{
                $id=input('param.id');
                $cover=input('param.cover',[]);
                if(count($cover)>0){
                    $cover=moveImage($cover,'exhibit',$id);
                }
                $detail=Db::table('exhibits')->where(['id'=>$id])->update([
                    // 'zone_class'=>input('param.zone_class'),
                    // 'zone'=>input('param.zone'),
                    // 'customize_code'=>input('param.customize_code'),
                    'title'=>input('param.title'),
                    'era'=>input('param.era'),
                    'category'=>input('param.category'),
                    'type'=>input('param.type'),
                    'cover'=>json_encode($cover),
                    'tex'=>input('param.tex'),
                    'style_mark'=>input('param.style_mark'),
                    'size'=>input('param.size'),
                    'angle'=>input('param.angle'),
                    'pieces'=>input('param.pieces'),
                    'price_desc'=>input('param.price'),
                    'remark'=>input('param.remark')
                ]);
                $redis=\think\facade\Cache::store('redis')->get('EXHIBIT_'.$id);
                $redis=json_decode(json_encode($redis),true);
                if($redis){
                    $data=Db::table('exhibits')->field('id,zone_class,zone,customize_code,cover,title,era,category,type,tex,style_mark,size,angle,check_in_at,remark,pieces,price,price_desc')
                        ->where(['id'=>$id])->find();
                    if($data['cover']){
                        $data['cover']=json_decode($data['cover'],true);
                        foreach($data['cover'] as $k=>$v){
                            $data['cover'][$k]='https://darong.storage.1415926.com.cn'.$v;
                        }
                    }else{
                        $data['cover']=[];
                    }
                    \think\facade\Cache::store('redis')->set('EXHIBIT_'.$id,$data,600);
                }
                $access_token=getAccessToken();
                $scene = 'exhibitId='.$id; // 场景值，可根据业务需要传递参数:cite[4]
                $page = 'pages/exhibit/detail'; // 扫描小程序码后进入的页面:cite[4]
                $savePath='/www/wwwroot/storage.darong1994.cn/tmp_wxacode/'.input('param.customize_code').'_'.input('param.title').'.png';
                $kk=setWxacode($access_token,$scene, $page, $savePath, 430);
                
                return json(['code'=>200,'message'=>'编辑成功','success'=>true]);

            }catch (Exception $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e]);
            }
        }
    }

    /**
     * 隐藏指定资源
     */
    public function setHideExhibitById(){
        if(Request::isPost()){
            $id=input('param.id');
            Db::table('exhibits')->where(['id'=>$id])->update([
                'is_hide'=>input('param.isHide',0)
            ]);
            return json(['code'=>200,'message'=>'设置成功','success'=>true]);
        }
    }

    /**
     * 上传图片
     */
    public function uploadImage(){
        if(Request::isPost()){
            $file = request()->file();
            try{
                
                validate(['image'=>'fileSize:2097152|fileExt:jpg,png,jpeg'])->check($file);
                $image = request()->file('image');
                $savename =\think\facade\Filesystem::disk('toStorageUrl')->putFile( '/tmp/exhibit', $image);
                // $site='http://1.12.76.149:15002';
                $site=self::storageStie;
                $url=$site.'/'.$savename;
                return json(['code'=>200,'success'=>true,'message'=>'上传成功','result'=>['site'=>$site,'savename'=>$savename,'url'=>$url]]);
            } catch (\think\exception\ValidateException $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e->getMessage()]);
            }
        }
    }
    
    /**
     * 更改活动状态
     */
    public function changeExhibitsStatus(){
        if(Request::isPost()){
            try{
                $param=input('param.');
                if(!(isset($param['id'])||isset($param['field'])||isset($param['value']))){
                    return json(['code'=>200,'success'=>false,'message'=>'参数错误']);
                }
                $detail=Db::table('exhibits')->where(['id'=>$param['id']])->update([
                    $param['field']=>$param['value']
                ]);
                return json(['code'=>200,'message'=>'设置成功','success'=>true,'param'=>input('param.')]);
            }catch (Exception $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e]);
            }
        }
    }
    
    //获取所有展品
    public function getAllExhibitsInCode(){
        if(Request::isPost()){
            $data=[];
            $list=Db::table('exhibits')->field('id,customize_code,title,ifnull(price_desc,"") as price_desc')
            ->select()->all();
            foreach ($list as $k=>$v){
                $data[$v['customize_code']]=[
                    'id'=>$v['id'],
                    'title'=>$v['title'],
                    'price_desc'=>$v['price_desc'],
                    'wxacode'=>'https://darong.1415926.com.cn/exhibitwxacode/'.$v['customize_code'].'_'.$v['title'].'.png'
                ];
            }
            return json(['code'=>200,'message'=>'获取成功','success'=>true,'result'=>['list'=>$data]]);
        }
    }
    
    //获取所有展品
    public function getAllExhibitsReturnCode(){
        if(Request::isPost()){
            $data=[];
            $list=Db::table('exhibits')->field('id,customize_code,title,ifnull(price_desc,"") as price_desc')
            ->select()->all();
            foreach ($list as $k=>$v){
                $data[$v['customize_code']]=[
                    'id'=>$v['id'],
                    'title'=>$v['title'],
                    'price_desc'=>$v['price_desc'],
                    'wxacode'=>'https://darong.1415926.com.cn/exhibitwxacode/'.$v['customize_code'].'_'.$v['title'].'.png'
                ];
            }
            return json(['code'=>200,'message'=>'获取成功','success'=>true,'result'=>['list'=>$data]]);
        }
    }
    
    
    public function getExhibitsByCode(){
        if(Request::isPost()){
            $exhibits=Db::table('exhibits')->field('id,customize_code,title')->where(['customize_code'=>input('param.code')])->find();
            return json(['code'=>200,'message'=>'获取成功','success'=>true,'result'=>$exhibits]);
        }
    }
    
    public function setExhibitsInfoByField(){
        if(Request::isPost()){
            try{
                $id=Request::post('id/s',0);
                $save=Request::post('save',[]);
                
                if(count($save)==0||$id==0){
                    return json(['code'=>200,'success'=>false,'message'=>'参数出错']);
                }
                Db::table('exhibits')->where(['id'=>$id])->update($save);
                $redis=\think\facade\Cache::store('redis')->get('EXHIBIT_'.$id);
                $redis=json_decode(json_encode($redis),true);
                if($redis){
                    $redis['price_desc']=$save['price_desc'];
                    $redis['is_show_price']=$save['price_desc']?1:0;
                    \think\facade\Cache::store('redis')->set('EXHIBIT_'.$id,$redis,600);
                }
                return json(['code'=>200,'message'=>'更新成功','success'=>true]);
            } catch (\think\exception\ValidateException $e) {
                return json(['code'=>200,'success'=>false,'message'=>'更新失败:'.$e->getMessage()]);
            }
        }
    }
}
